package secondBrush.list;

/**
 * 设计链表
 */

public class MyLinkedList {

    class ListNode{
        int val;
        ListNode next;

        public ListNode() {
        }

        public ListNode(int val) {
            this.val = val;
        }
    }

    int size;
    ListNode head;

    public MyLinkedList() {
        size = 0;
        head = new ListNode(0);
    }

    public int get(int index) {

        if (index < 0 || index >= size) {
            return -1;
        }

        ListNode cur = head;
        //遍历找到节点
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }

        return cur.next.val;




    }

    public void addAtHead(int val) {
        ListNode newNode = new ListNode(val);
        newNode.next = head.next;
        head.next = newNode;
        size++;

    }

    public void addAtTail(int val) {

        ListNode cur = head;
        while (cur.next != null) {
            cur = cur.next;
        }
        ListNode newNode = new ListNode(val);

        cur.next = newNode;
        size++;


    }

    public void addAtIndex(int index, int val) {
        if (index > size) {
            return;
        }
        ListNode toAdd = new ListNode(val);
//        if (index == size - 1) {
//            addAtTail(val);
//        }
        ListNode cur = head;
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        toAdd.next = cur.next;
        cur.next = toAdd;
        size++;

    }

    public void deleteAtIndex(int index) {
        if (index < 0 || index >= size) {
            return;
        }
        ListNode cur = head;
        //找到待删除的节点
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }

        cur.next = cur.next.next;
        size--;

    }

}
